﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using InformationCenter.Models;
using InformationCenter.SQLHelper;

namespace InformationCenter.Controllers
{
    public class ArticleListsController : Controller
    {
        private WebDbContext db = new WebDbContext();


        // GET: ArticleLists
        public ActionResult Index()
        {
            return View(db.ArticleLists.ToList());
        }

       // [HttpGet]
       //public ActionResult Index(string category)
       // {
   

       //     var search = db.ArticleLists.FirstOrDefault(p=>p.Category==category);

       //     return View(search);
       // }



        // GET: ArticleLists/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ArticleList articleList = db.ArticleLists.Find(id);
            if (articleList == null)
            {
                return HttpNotFound();
            }
            return View(articleList);
        }

        // GET: ArticleLists/Create
        public ActionResult Create()
        {
             ViewData["Type"] = GenerateList();
            return View();
        }

        // POST: ArticleLists/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Include = "Id,Name,SeoKeyword,SeoSummary,Picture,Category,Writer,Context,CreateDateTime,ReadCount")] ArticleList articleList)
        {
            if (ModelState.IsValid)
            {
                Stream uploadStream = null;
                FileStream fs = null;
                try
                {
                    //文件上传，一次上传1M的数据，防止出现大文件无法上传  
                    HttpPostedFileBase postFileBase = Request.Files["Picture"]; //Request.Files["Picture"]; input 中的Name
                    uploadStream = postFileBase.InputStream;
                    int bufferLen = 1024;
                    byte[] buffer = new byte[bufferLen];

                    string fileName = Path.GetFileName($"{DateTime.Now.Ticks}{ postFileBase.FileName}");
                    string baseUrl = Server.MapPath("/");
                    string uploadPath = baseUrl + @"UploadImg\";
                    
                    fs = new FileStream($"{ uploadPath}{ fileName }", FileMode.Create, FileAccess.ReadWrite);

                    while ((uploadStream.Read(buffer, 0, bufferLen)) != 0)
                    {
                        fs.Write(buffer, 0, bufferLen);
                        fs.Flush();
                    }

                    //保存页面数据，上传的文件只保存路径  
                    string image = "/UploadImg/" + fileName;
                
                        db.ArticleLists.Add(articleList);
                        articleList.Picture = image;
                        articleList.ReadCount = 0;
                        articleList.CreateDateTime = DateTime.Now;
                        db.SaveChanges();
                    }
                
                catch (Exception ex)
                        {
                            ex.StackTrace.ToString();
                        }
                        finally
                        {
                            if (null != fs)
                            {
                                fs.Close();
                            }
                            if (null != uploadStream)
                            {
                                uploadStream.Close();
                            }
                        }

            return RedirectToAction("Index");
            }

            return View(articleList);
        }




        // GET: ArticleLists/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ArticleList articleList = db.ArticleLists.Find(id);
            if (articleList == null)
            {
                return HttpNotFound();
            }
            ViewData["Type"] = GenerateList();
            return View(articleList);
        }

        // POST: ArticleLists/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit([Bind(Include = "Id,Name,SeoKeyword,SeoSummary,Picture,Category,Writer,Context,CreateDateTime,ReadCount")] ArticleList articleList)
        {
            if (ModelState.IsValid)
            {
                Stream uploadStream = null;
                FileStream fs = null;
                try
                {
                    //文件上传，一次上传1M的数据，防止出现大文件无法上传  
                    HttpPostedFileBase postFileBase = Request.Files["Picture"]; //Request.Files["Picture"]; input 中的Name
                    uploadStream = postFileBase.InputStream;
                    int bufferLen = 1024;
                    byte[] buffer = new byte[bufferLen];

                    string fileName = Path.GetFileName($"{DateTime.Now.Ticks}{ postFileBase.FileName}");
                    string baseUrl = Server.MapPath("/");
                    string uploadPath = baseUrl + @"UploadImg\";

                    fs = new FileStream($"{ uploadPath}{ fileName }", FileMode.Create, FileAccess.ReadWrite);

                    while ((uploadStream.Read(buffer, 0, bufferLen)) != 0)
                    {
                        fs.Write(buffer, 0, bufferLen);
                        fs.Flush();
                    }

                    //保存页面数据，上传的文件只保存路径  
                    string image = "/UploadImg/" + fileName;

                    db.Entry(articleList).State = EntityState.Modified;
                    articleList.Picture = image;
                    db.SaveChanges();
                }

                catch (Exception ex)
                {
                    ex.StackTrace.ToString();
                }
                finally
                {
                    if (null != fs)
                    {
                        fs.Close();
                    }
                    if (null != uploadStream)
                    {
                        uploadStream.Close();
                    }
                }

                return RedirectToAction("Index");
            }
            return View(articleList);
        }

        // GET: ArticleLists/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ArticleList articleList = db.ArticleLists.Find(id);
            if (articleList == null)
            {
                return HttpNotFound();
            }
            return View(articleList);
        }

        // POST: ArticleLists/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            ArticleList articleList = db.ArticleLists.Find(id);
            db.ArticleLists.Remove(articleList);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        public  SelectList GenerateList()
        {
            var category = db.Categories.ToList();

            SelectList generateList = new SelectList(category, "Name", "Name");

            return generateList;
        }
    }
}
